package com.baozi.order.converter;

import com.baozi.order.dto.OrderDto;
import com.baozi.order.entity.OrderDetail;
import com.baozi.order.enums.ResultEnum;
import com.baozi.order.exception.OrderException;
import com.baozi.order.from.OrderFrom;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderFrom2OrderDto {

    public static OrderDto convert(OrderFrom orderFrom) {
        Gson gson = new Gson();
        OrderDto orderDto = new OrderDto();
        orderDto.setBuyerName(orderFrom.getName());
        orderDto.setBuyerPhone(orderFrom.getPhone());
        orderDto.setBuyerAddress(orderFrom.getAddress());
        orderDto.setBuyerOpenid(orderFrom.getOpenid());
        List<OrderDetail> orderDetail = new ArrayList<>();
        try {
            orderDetail=gson.fromJson(orderFrom.getItems(),
                    new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (JsonSyntaxException e) {
            log.info("json转换错误={}", orderFrom.getItems());
            throw new OrderException(ResultEnum.PARAM_ERROR);
        }
        orderDto.setList(orderDetail);
        return orderDto;
    }

}
